package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.db.UserDatabase
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.InputFilterUtils
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.AddDeliveryInfoFragmentBinding
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.AddDeliveryInfoHistoryBean
import com.example.shushiyunsst.util.ADD_DELIVERY_INFO
import com.example.shushiyunsst.util.DELIVERY_INFO_HISTORY_BEAN

import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import org.greenrobot.eventbus.EventBus

@Route(path = ADD_DELIVERY_INFO)
class AddDeliveryInfoFragment : BaseDataBindingFragment<AddDeliveryInfoFragmentBinding>(),
    View.OnClickListener, OnTextListener {

    private var consignee = ""

    private var contactPhone = ""

    private var deliveryAddress = ""

    private val selectedAreaLs = mutableListOf<AreaItemBean?>()

    @JvmField
    @Autowired(name = DELIVERY_INFO_HISTORY_BEAN)
    var deliveryInfoHistoryBean: AddDeliveryInfoHistoryBean? = null

    override fun layoutId() = R.layout.add_delivery_info_fragment

    private val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.add_delivery_address)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        InputFilterUtils.setEditTextInhibitInputSpaChat(viewBinder.consignee)

        InputFilterUtils.setEditTextInhibitInputSpaChat(viewBinder.deliveryAddress22)


        viewBinder.deliveryInfoHistoryBean = deliveryInfoHistoryBean

        consignee = deliveryInfoHistoryBean?.recName ?: ""

        contactPhone = deliveryInfoHistoryBean?.recPhone ?: ""

        viewBinder.onViewClick = this

        viewBinder.onTextListener = this

        deliveryAddress = deliveryInfoHistoryBean?.areaSub ?: ""

        viewBinder.settingDefault.isChecked = deliveryInfoHistoryBean?.isDefault == 1
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.select_location -> {
                XPopup.Builder(_mActivity)
                    .hasShadowBg(false)
                    .asCustom(
                        SelectLocationPop(_mActivity)
                            .setOnSelectListener(object : SelectLocationPop.OnSelectListener {
//                                override fun onSelected(string: String) {
//                                    viewBinder.selectLocation.text = string
//                                }

                                override fun onSelected(ls: List<AreaItemBean?>) {
                                    selectedAreaLs.clear()
                                    selectedAreaLs.addAll(ls)
                                    viewBinder.selectLocation.text = getSelectLocationName()
                                }
                            })
                    )
                    .show()
            }
            R.id.tv_done -> {
                if (checkInfo()) {
                    if (deliveryInfoHistoryBean == null) {
                        addDelivery()
                    } else {
                        editorDelivery()
                    }

                }
            }
        }
    }

    private fun getSelectLocationName(): String {

        var string = StringBuilder()
        for (e in selectedAreaLs) {
            string.append(e?.areaName?.replace(",","")).append(",")
        }

        if (string.lastIndexOf(",") != string.indexOf(",")) {
            string = string.deleteCharAt(string.lastIndexOf(","))
        }

        return string.toString()
    }

    private fun getAreaIds(): String {
        if (selectedAreaLs.size <= 0) return deliveryInfoHistoryBean?.areaIds.toString()

        var string = StringBuilder()
        for (e in selectedAreaLs) {
            string.append(e?.aid).append(",")
        }

        if (string.lastIndexOf(",") != string.indexOf(",")) {
            string = string.deleteCharAt(string.lastIndexOf(","))
        }

        return string.toString()
    }

    private fun getAreaName(): String {
        if (selectedAreaLs.size <= 0)
            return "${deliveryInfoHistoryBean?.areaSuper.toString()},$deliveryAddress"

        return "${getSelectLocationName()},$deliveryAddress"
    }

    private fun editorDelivery() {


        val isDefault = if (viewBinder.settingDefault.isChecked) "1" else "0"

        val maps = mapOf(
            "aid" to deliveryInfoHistoryBean?.aid,
            "isDefault" to isDefault,
            "recAddr" to getAreaName(),
            "recName" to consignee,
            "areaIds" to getAreaIds(),
            "recPhone" to contactPhone,
            "uid" to user?.uid,
        )

        RestClient.builder()
            .url(R.string.updateShopAddr)
            .raw(JSON.toJSONString(maps))
            .success {

                EventBus.getDefault().post(MessageWrap.getInstance(ADD_DELIVERY_INFO))

                onBackPressedSupport()

            }.failure {
                normalShortToast(_mActivity, R.string.sending_failed)
//                Toast.makeText(_mActivity, R.string.sending_failed, Toast.LENGTH_SHORT)
//                    .show()
            }.error { _, msg ->
                normalShortToast(_mActivity, msg)
//                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build()
            .post()
    }

    private fun addDelivery() {

        val isDefault = if (viewBinder.settingDefault.isChecked) "1" else "0"

        val maps = mapOf(
            "isDefault" to isDefault,
            "recAddr" to getAreaName(),
            "recName" to consignee,
            "recPhone" to contactPhone,
            "areaIds" to getAreaIds(),
            "uid" to user?.uid,
        )
        RestClient.builder()
            .url(R.string.saveShopAddress)
            .raw(JSON.toJSONString(maps))
            .success {

                EventBus.getDefault().post(MessageWrap.getInstance(ADD_DELIVERY_INFO))

                onBackPressedSupport()

            }.failure {
                normalShortToast(_mActivity, R.string.sending_failed)
//                Toast.makeText(_mActivity, R.string.sending_failed, Toast.LENGTH_SHORT)
//                    .show()
            }.error { _, msg ->
                normalShortToast(_mActivity, msg)
//                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .build()
            .post()
    }

    private fun checkInfo(): Boolean {
        val text = viewBinder.selectLocation.text
        var flag = true
        if (contactPhone.isEmpty() || contactPhone.length < 11) {
            Toast.makeText(_mActivity, "请输入手机号码", Toast.LENGTH_SHORT).show()
            flag = false
        } else if (consignee.isEmpty()) {
            Toast.makeText(_mActivity, "请输入收货人姓名", Toast.LENGTH_SHORT).show()
            flag = false
        } else if (deliveryAddress.isEmpty()) {
            Toast.makeText(_mActivity, "请输入具体地址", Toast.LENGTH_SHORT).show()
            flag = false
        } else if (text.isEmpty()) {
            Toast.makeText(_mActivity, "请选择省市区", Toast.LENGTH_SHORT).show()
            flag = false
        }
        return flag
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.consignee -> {
                consignee = s.toString()
            }
            R.id.contact_phone -> {
                contactPhone = s.toString()
            }
            R.id.delivery_address_22 -> {
                deliveryAddress = s.toString()
            }
        }
    }
}